package com.example.demo.controller;

import com.example.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;


@Controller
public class StudentController {

    private static Map<String, Student> students = new HashMap<>();

    static {
        Student s1 = new Student("1", "tony");
        students.put(s1.getId(),s1);
        Student s2 = new Student("2", "jerry");
        students.put(s2.getId(),s2);
    }

    @RequestMapping("list")
    public String list(ModelMap map) {
        map.put("studentList", students.values());
        return "list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
//        System.out.println("id: "+id);
          students.remove(id);
//        students.remove(Integer.parseInt(id)-1);
//        int index = Integer.parseInt(id) - 1;
//        students.remove(index);
          return "redirect:/list";
    }

    @RequestMapping("create")
    public String create() {
        return "create";
    }


    @RequestMapping("save")
    public String save(Student s){
//        System.out.println(s.getName());
        if(s.getId()==null){
            s.setId(String.valueOf(students.size() + 1));
        }
//        s.setId(String.valueOf(students.size() + 1));
//        students.add(s);
        students.put(s.getId(),s);
        return "redirect:/list";
        }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map){
//        Student s = students.get(Integer.parseInt(id)-1);
        Student s = students.get(id);
        map.put("student",s);
        return "update";
    }
}

